// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  try {
    var word_id = 0;
    var count = 0;
    var log = 0;

    //通过JS的方法获取当前年月日
    var date = new Date();
    date = new Date(date.getTime() + 8 * 60 * 60 * 1000);
    //获取年份  
    const Y = date.getFullYear();
    //获取月份  
    const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //获取当日日期 
    const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();



    let first = await db.collection('location').where({
      user_id: wxContext.OPENID,
    }).count();

    if (first.total == 0) { //第一次打开背单词界面
      log = 1;
      word_id = 0;
      count = 0;
      return {
        _log: log,
        word_id: word_id,
        count: count,
        jap: null,
        kana: null,
        cixing: null,
        meaning: null,
        level: null,
        star: null,
      }

    } else { //不是第一次打开

      let today = await db.collection('location').where({
        user_id: wxContext.OPENID,
        time: {
          year: Y,
          month: M,
          day: D,
        }
      }).get();

      if (today.data[0] == null) { //today.data[0]==null 上次背单词不是今天
        log = 2;
        const yes = await cloud.callFunction({
          // 要调用的云函数名称
          name: 'last',
          // 传递给云函数的参数
          data: {
            openid: wxContext.OPENID,
          }
        });
        word_id = yes.result.word_id;
        count = 0;

      } else { //上次背单词是今天
        //上次背单词是今天，则word_id为今天的word_id
        word_id = today.data[0].word_id;
        if (first.total == 1) { //今天第一天
          log = 3;
          count = word_id;
        } else { //今天不是第一天
          log = 4;
          // return{
          //   _log:log,
          //   date:date,
          //   D:D,
          // }
          const yes = await cloud.callFunction({
            // 要调用的云函数名称
            name: 'last',
            // 传递给云函数的参数
            data: {
              openid: wxContext.OPENID,
            }
          });
          count = word_id - yes.result.word_id;
        }
      }
    }
    const res = await cloud.callFunction({
      // 要调用的云函数名称
      name: 'word',
      // 传递给云函数的参数
      data: {
        word_id: word_id,
      }
    });

    return {
      _log: log,
      word_id: word_id,
      count: count,
      jap: res.result.jap,
      kana: res.result.kana,
      cixing: res.result.cixing,
      meaning: res.result.meaning,
      level: res.result.level,
      star: res.result.star,
    }
  } catch (e) {
    console.error(e);
  }


}